package com.rongmai.db.utils;

import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author zhenhua.sun
 * @date 10/22/17
 */
public class BeanUtils {

    private static final String GET = "get";

    public static String bean2UrlUtil(Object t){
        StringBuffer urlParam = new StringBuffer();
        Field[] fields = t.getClass().getDeclaredFields();
        for (Field field : fields){
            String name = field.getName();
            String value = getFieldVal(name,t);
            if(!StringUtils.isEmpty(value)){
                urlParam.append("&"+name+"="+value);
            }
        }
        return urlParam.toString();
    }

    /**
     * 获取属性对应的值
     * @return
     */
    private static String getFieldVal(String field, Object t){
        String getMethod = getMethodFun(field);
        String value = "";
        try {
            Method method = t.getClass().getMethod(getMethod);
            if(method != null) {
                value = (String) method.invoke(t);
            }
        } catch (Exception e) {
        }
        return value;
    }

    /**
     * 获取属性的get 方法
     * @param field
     * @return
     */
    private static String getMethodFun(String field) {
        return BeanUtils.GET+ StringUtils.capitalize(field);
    }

}
